#!/usr/bin/env python 
# coding:utf-8
# @Time :11/15/18 17:30

import requests
import base64


class ImgRecognitionService(object):

    def __init__(self, log=None):
        if not log:
            print "请添加log设置"
            raise BaseException
        self.log = log

    def discern(self, *args, **kwargs):
        pass

    def is_binary_string(self, content):
        """
        判断文件是否是二进制文件
        from: https://stackoverflow.com/questions/898669/how-can-i-detect-if-a-file-is-binary-non-text-in-python
        """
        textchars = bytearray({7, 8, 9, 10, 12, 13, 27} | set(range(0x20, 0x100)) - {0x7f})
        recg = lambda bytes: bool(bytes.translate(None, textchars))
        return recg(content)


class BaiduImgRecognitionService(ImgRecognitionService):

    __BAIDU_TOKEN_URL = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id={AK}&client_secret={CK}"
    __BAIDU_OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/general"
    # __BAIDU_OCR_URL = "https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic"

    # other params
    __BAIDU_AK = "lj7bGQB5vM1KmK9DHTPHVsjQ"
    __BAIDU_CK = "VNDY9M79qpX75hpN9uM7EUdgd16xQbcU"

    def __init__(self, log):
        super(BaiduImgRecognitionService, self).__init__(log=log)
        self.__access_token = self.__get_baidu_token()

    def discern(self, content):
        """
        :param content: 二进制文件
        :return:
        """

        if not self.is_binary_string(content):
            self.log.error("请传入正确的识别文件，识别文件只允许二进制文件")
            return

        image_base64_encode = base64.b64encode(content)
        form_data = {"image": image_base64_encode}
        ocr_resp = requests.post(self.__BAIDU_OCR_URL, params={"access_token": self.__access_token}, data=form_data).json()
        if ocr_resp.get("words_result_num") == 1:
            return ocr_resp["words_result"][0].get("words")
        self.log.info("识别失败...")
        self.log.info("识别失败的具体信息是：{}".format(ocr_resp))

    def __get_baidu_token(self):
        headers = {"Content-Type": "application/json; charset=UTF-8"}
        access_resp = requests.get(self.__BAIDU_TOKEN_URL.format(AK=self.__BAIDU_AK, CK=self.__BAIDU_CK),
                                   headers=headers)
        access_token = access_resp.json().get("access_token")
        return access_token


if __name__ == '__main__':
    pass